package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AdminMapper;
import com.itheima.dao.TodoMapper;
import com.itheima.pojo.Todo;
import com.itheima.service.TodoService;
import com.itheima.utils.IdWorker;
import com.itheima.utils.Result;
import com.itheima.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TodoServiceImpl implements TodoService {
    @Autowired
    private TodoMapper todoMapper;

    @Autowired
    private AdminMapper adminMapper;


    @Autowired
    private IdWorker idWorker;

    //添加
    @Override
    public int add(Todo todo,String username) {

        todo.setCreateTime(new Date());
        todo.setUpdateTime(new Date());
        todo.setUid(String.valueOf(idWorker.nextId()));
         String uid = adminMapper.selectByName(username);
         todo.setAdminUid(uid);

        int i = todoMapper.insert(todo);

        return i;
    }

    //删除
    @Override
    public Result delete(Todo todo) {
        todoMapper.delete(todo);
        return new Result<>(StatusCode.SUCCESS,"删除成功");
    }

    //编辑
    @Override
    public Result edit(Boolean done,String uid,String text) {
        Todo selectOne = todoMapper.selectByPrimaryKey(uid);
        if (selectOne==null){
            return new Result<>(StatusCode.FAIL,"没有数据，无法修改");
        }

        Todo todo = new Todo();
        if (done){
            todo.setDone(1);
        }
        todo.setUid(uid);
        todo.setText(text);
        todo.setUpdateTime(new Date());
        todo.setStatus(1);
        todoMapper.updateByPrimaryKeySelective(todo);
        return new Result<>(StatusCode.SUCCESS,"编辑成功");
    }


    //查询所有
    @Override
    public Page<Todo> getList(Todo todo) {
        PageHelper.startPage(todo.getCurrentPage(),todo.getPageSize());
        List<Todo> todoList = todoMapper.select(todo);
        return (Page<Todo>) todoList;
    }
}
